package com.dirven.game;

public class IntervalTimer {

	long lastUpdated = 0;
	long interval;
	
	boolean paused = false;
	boolean stopped = false;
	private long pauseTime;
	
	public IntervalTimer(long interval) {
		this.interval = interval;
	}
	
	/**
	 * Start the interval timer
	 */
	public void start() {
		stopped = false;
		lastUpdated = System.currentTimeMillis();
	}
	
	/**
	 * Check if at the next interval
	 * @return
	 */
	public boolean atNextInterval() {
		
		if(stopped || paused) {
			return false;
		}
		
		long currentTime = System.currentTimeMillis();
		long tDiff = currentTime - lastUpdated;
		
		if(tDiff >= interval) {
			lastUpdated = currentTime;
			return true;
		} else {
			return false;
		}
		
	}
	
	/**
	 * Stop the interval timer.
	 */
	public void stop() {
		stopped = true;
	}
	
	/**
	 * Resume the interval timer.
	 */
	public void resume() {
		if(paused) {
			paused = false;
			long resumeTime = System.currentTimeMillis();
			long pauseDuration = resumeTime - pauseTime;
			
			// Add the duration the interval timer was paused for to compensate for the
			// extra time between the last interval update and the current time.
			lastUpdated += pauseDuration;
			pauseTime = 0;
		}
	}

	/**
	 * Pause the interval timer.
	 */
	public void pause() {
		if(paused == false) {
			paused = true;
			pauseTime = System.currentTimeMillis();
		}
	}
	
}
